package com.salmon.weixin.utils;

import com.salmon.weixin.menu.Menu;
import com.salmon.weixin.po.AccessToken;
import com.salmon.weixin.po.MenuResult;
import org.springframework.http.HttpEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

public class WeixinUtils {

    private static final String APP_ID = "wxc92321d8f41c8e65";

    private static final String APP_SECRET = "2fd0c6098a13704cb602bc3df6d14287";

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s";

    private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";

    private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s";

    private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";

    private static RestTemplate restTemplate = new RestTemplate();

    static {
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    /**
     * 获取accessToken, 正式应用时请把AccessToken进行缓存， 默认 2小时过期
     */
    public static AccessToken getAccessToken() {
        String url = String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET);
        return restTemplate.getForObject(url, AccessToken.class);
    }

    /**
     * 创建菜单
     * @param accessToken accessToken
     * @param menu 序列化后的 menu字符串
     * @return
     */
    public static MenuResult createMenu(String accessToken, String menu) {
        String url = String.format(CREATE_MENU_URL, accessToken);
        HttpEntity<String> formEntity = new HttpEntity<>(menu);
        return restTemplate.postForObject(url, formEntity, MenuResult.class);
    }

    /**
     * 查询菜单
     * @param accessToken accessToken
     * @return
     */
    public static Menu queryMenu(String accessToken) {
        String url =  String.format(QUERY_MENU_URL, accessToken);
        return restTemplate.getForObject(url, Menu.class);
    }
    /**
     * 删除菜单
     * @param accessToken accessToken
     * @return
     */
    public static MenuResult deleteMenu(String accessToken) {
        String url = String.format(DELETE_MENU_URL, accessToken);
        return restTemplate.getForObject(url, MenuResult.class);
    }




}
